#!/usr/bin/env python

import sys, os, getopt
from shutil import move
from threading import Thread

OPT = { "fstree_path" : "/var/baubau", "rpmbuild_path":"/var/tmp/files2rpm_rpmbuild", "files_fp":None, "pkg_path":None,
	"rpm_name":"fstree", "rpm_ver":"1.0", "rpm_rel":"0", "rpm_path":".", "arch":"noarch", "file_path":None }

def _mkdir(newdir):
    """works the way a good mkdir should :)
        - already exists, silently complete
        - regular file in the way, raise an exception
        - parent directory(ies) does not exist, make them as well
    """
    if os.path.isdir(newdir):
        pass
    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)
    else:
        head, tail = os.path.split(newdir)
        if head and not os.path.isdir(head):
            _mkdir(head)
        #print "_mkdir %s" % repr(newdir)
        if tail:
            os.mkdir(newdir)

def usage():
        print "Usage: files2rpm [OPTION]"
        print "Build an RPM containing files from a specified list."
        print "Optionally, add a dependency to packages from list (formatted as \"rpm -qa\"."
        print ""
        print "  -i, --files <file>      file containing list of files to be archive"
        print "  -p, --packages [<file>] add a dependency for packages from file"
	print "                          if <file> is \"auto\", use output of \"rpm -qa\""
        print "  -a, --arch <arch>       specify an architecture (default is noarch)"
	print "  -o, --out <file>        output file"
	return
        print ""
        print "  -preserve original attributes (default)"
        print "  -preserve attributes of files to be overwritten"
        print ""


try:
	opts, args = getopt.getopt(sys.argv[1:], "hi:p:a:o:", ["help", "files", "packages"])
except getopt.GetoptError:
	usage()
	sys.exit(2)

for opt, arg in opts:
	if opt in ("-h", "--help"):
		usage()
		sys.exit()

	elif opt in ("-i", "--files"):
		OPT["files_fp"] = open(arg,"r")
		OPT["file_path"] = arg

	elif opt in ("-p", "--packages"):
		if arg == "auto":
			os.system("rpm -qa > /tmp/rpmqa")
			arg = "/tmp/rpmqa"
		OPT["pkg_path"] = arg

	elif opt in ("-a", "--arch"):
		OPT["arch"] = arg

	elif opt in ("-o", "--outdir"):
		arg = os.path.abspath(arg)
		OPT["rpm_path"] = arg
		OPT["rpmbuild_path"] = arg + "/rpmbuild_tmp"

if not OPT["files_fp"]:
	usage()
	sys.exit()

_mkdir(OPT["rpmbuild_path"] + "/SPECS")
_mkdir(OPT["rpmbuild_path"] + "/BUILD")
_mkdir(OPT["rpmbuild_path"] + "/RPMS")

OPT["rpmbuild_spec_path"] = "%s/SPECS/%s.spec" % ( OPT["rpmbuild_path"], OPT["rpm_name"] )

fp=open(OPT["rpmbuild_spec_path"],"w")

fp.write("""%define _unpackaged_files_terminate_build 0
%define _topdir """ + OPT["rpmbuild_path"] + """
#%define debug_package %{nil}
%debug_package %{nil}
%define __prelink_undo_cmd %{nil}
%define __os_install_post %{nil}

Summary: A multithreaded backup utility to include modified files from packages (using RPMdb) and new files.
Name: """ + OPT["rpm_name"] + """
Version: """ + OPT["rpm_ver"] + """
Release: """ + OPT["rpm_rel"] + """
License: GPL
Group: Development/Debuggers
BuildArch: """ + OPT["arch"] + """
BuildRoot: %{_builddir}/%{name}-root
""")

if OPT["pkg_path"]:
	pkgfp = open(OPT["pkg_path"],"r")
	for line in pkgfp:
		line = line.strip().rsplit('-', 2)
		fp.write("Requires: %s = %s-%s\n" % (line[0], line[1], line[2]) )
#		fp.write("Requires: %s = %s\n" % (line[0], line[1]) )
	pkgfp.close()

fp.write("""URL: http://www.navid.it
Packager: navid@navid.it
%description
baubau is a multithreaded backup utility which walks the file-system
searching for files belonging to packages which have been modified
(using RPMdb) and for new files (which don't belong to any package).

This way it is possible to only archive files which otherwise would
be unrecoverrable.
%prep
#rm -rf $RPM_BUILD_ROOT
if [ ! -d $RPM_BUILD_ROOT""" + OPT["fstree_path"] + """ ]; then
    mkdir -p $RPM_BUILD_ROOT""" + OPT["fstree_path"] + """
fi

%build

%install

%clean
rm -rf $RPM_BUILD_ROOT

%files
""" + OPT["fstree_path"] + """/fstree.tar

%doc
#/var/baubau/fstree/README

%changelog
* Tue Mar  13 2007  Navid Sheikhol-Eslami <navid@navid.it>
- Initial release
""")

fp.close()

os.system('rpmbuild --clean "%s"' % OPT["rpmbuild_spec_path"])
os.system('rpmbuild -bp "%s"' % OPT["rpmbuild_spec_path"])

os.system('tar Tcf %s %s/BUILD/%s-root/%s/fstree.tar' % (OPT["file_path"], OPT["rpmbuild_path"], OPT["rpm_name"], OPT["fstree_path"]))

os.system('rpmbuild -bb "%s"' % OPT["rpmbuild_spec_path"])

os.system('rpmbuild --clean "%s"' % OPT["rpmbuild_spec_path"])

#move("%s/RPMS/%s/%s-%s-%s.%s.rpm" % (OPT["rpmbuild_path"], OPT["arch"], OPT["rpm_name"], OPT["rpm_ver"], OPT["rpm_rel"], OPT["arch"]), OPT["rpm_path"])
